package com.mscsoft.brainpower.server.service;

import java.util.HashMap;
import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import com.mscsoft.brainpower.server.domain.*;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.*;

@RestController
public class MailService {
    // 发件邮箱
    @Value("${spring.mail.username}")
    private String from;
    @Resource
    private JavaMailSender mailSender;
    // 上次发送时间
    private HashMap<String, Long> lastTimes = new HashMap<>();
    private MimeMessage message;

    /** 发送邮件给to 主题为subject 正文为text */
    public Msg<Object> sendMail(String to, String subject, String text) {
        long currentTime = System.currentTimeMillis();
        long lastTime = lastTimes.containsKey(to) ? lastTimes.get(to) : 0;
        if (currentTime >= lastTime + 60 * 1000) {// 相同邮箱两次发送间隔不能小于一分钟
            lastTimes.put(to, currentTime);
            try {
                message = mailSender.createMimeMessage();
                MimeMessageHelper helper = new MimeMessageHelper(message, true);
                helper.setFrom(from);
                helper.setTo(to);
                helper.setSubject(subject);
                helper.setText(text, true);
                new Thread() {
                    @Override
                    public void run() {
                        mailSender.send(message);
                    }
                }.start();
                return new Msg<>();
            } catch (MessagingException e) {
                return new Msg<>(500, Msg.s500);
            }
        } else {
            return new Msg<>(403, Msg.s403);
        }
    }
}
